var $ = getApp().globalData.eui;
var biz = require("../../biz.js");
var Decimal = require("../../decimal.js");

$.page({
    data: {
        "product": {},
        "pinsku": null, //用于主图显示的拼团
        "detail": [],
        "isShow": false, //是否显示底部弹窗
        "showPin": false, //是否显示拼团选择内容
        fromuser: 0, //上级分销用户
        isdist:0,//当前用户是否为分销商
        isvip:0,

        //用于显示的产品基本信息，当usesku时用默认sku的相应参数代替
        "productDisplay": {
            "price": 0,
            "marketprice": 0,
            "icon": ""
        },

        "pinexpiretime": "", //拼团结束时间，用于倒计时
        "num": 1,

        "skusn": "",
        "skuprops": [],
        "skus": [],
        "pins": [], //经过排序后的拼团列表，价格低的优先
        "buynow": false,
        "kaituan": false,
        "cartCount": 0,
        "inpintime": false, //是否在可开团的有效期内
        "usericon": $.getConfig("image_root") + "/usericonw.png",
        "rightarrow": $.getConfig("image_root") + "/rightarroww.png",
        "timerPin": 0,
        //剩余时间倒计时
        "iDay": 0,
        "iHour": 0,
        "iMinute": 0,
        "iSecond": 0,
        cursku: {
            "icon": "",
            "sn": "",
            "price": 0,
            "marketprice": 0,
            "id": 0
        },
        curUser: {}, //当前登录用户信息
        fromuser:0,
        skutool: biz.SkuTool.create()
    },
    onLoad: function (options) {

        var me = this;

        var id = 0;

        var pricefield = "saleprice";
        var fromUser=0;
        var bindtype=0;

        getApp().getLoginUser(function (oUser) {
            me.setData({
                "curUser":oUser,
                "isdist":$.toInt(oUser.isdist),
                //"isvip":($.toInt(oUser.isvip) || $.toInt(oUser.isdist))
            });

            if (options.scene) {
                var scene = decodeURIComponent(options.scene);
                if (scene.indexOf("dist:") === 0) {
                    var str = scene.substr(5);
                    var tmpArr = $.split(str, "_");
                    id = $.toInt(tmpArr[0]);
                    fromUser = $.toInt(tmpArr[1]);
                    bindtype=1;
                    me.setData({"isvip":1});
                } else {
                    id = $.toInt(scene);
                }

            } else if(options.share){
                var share = $.fromJson( decodeURIComponent(options.share) );
                id = $.toInt(share.id);
                fromUser = $.toInt(share.fromUser);
                var isvip = $.toInt(share.isvip);
                bindtype=0;
                $.log("收到分享来的产品 id="+id+" fromUser="+fromUser+" isvip="+share.isvip);
                me.setData({"isvip":isvip});
            } else {
                id = $.toInt(options.id);
            }

            me.setData({"fromuser":fromUser});

            $.api("mall.Product.Load", {
                id: id
            })
                .then(function (oProduct) {

                    oProduct.usedist = $.toInt(oProduct.usedist); //是否启用分销

                    if (oProduct.usedist) {
                        if (me.data.fromuser || me.data.isvip) {
                            pricefield = "vipprice";
                        }

                        $.log("fromUser="+fromUser);
                        if( fromUser ){
                            me.setData({
                                "fromuser": fromUser
                            });
                            if( oUser && $.toInt(oUser.id)){
                                $.log("当前已登录，立即绑定");
                                $.api("mall.User.Bind", {
                                    pid: fromUser,
                                    bindtype:bindtype
                                })
                                    .then(function (value) {

                                    });
                            }else{
                                $.log("记下，登录后绑定");
                                $.setKey("needBindUser", fromUser).then(function (value) {
                                    //do nothing;
                                });
                            }

                        }
                    }

                    me.setData({
                        "product": oProduct,
                        "detail": $.fromJson(oProduct.detail)
                    });

                    me.updateCartCount();

                    $.api("mall.Product.LoadSkuProps", {
                        id: id
                    })
                        .then(function (skuprops) {
                            $.each(skuprops, function (skp) {
                                skp.style = $.toInt(skp.style);
                            });
                            me.setData({
                                "skuprops": skuprops
                            });
                            return $.api("mall.Product.LoadSkus", {
                                id: id
                            });
                        })
                        .then(function (skus) {
                            $.log("====> pricefield=" + pricefield);
                            if (pricefield != "saleprice") {
                                $.each(skus, function (sku) {
                                    sku.saleprice = sku.vipprice;
                                })
                            }

                            var pinexpiretime = "";
                            var pinprice = -1;
                            var pinsku = null;
                            var oPins = {};
                            var pins = [];
                            $.each(skus, function (sku) {
                                sku.pincount = $.toInt(sku.pincount);
                                sku.pintype = $.toInt(sku.pintype);
                                sku.usepin = $.toInt(sku.usepin);
                                sku.pinprice = $.toFloat(sku.pinprice);
                                sku.saleprice = $.toFloat(sku.saleprice);

                                if (sku.usepin && $.convertDateFromString(sku.pinendtime) > (new Date())) oPins[sku.pinprice] = sku;
                                if (sku.usepin) sku.shenprice = (sku.saleprice - sku.pinprice).toFixed(2);

                                if (sku.usepin && $.convertDateFromString(sku.pinendtime) > (new Date())) {
                                    if (pinprice < 0) pinsku = sku;
                                    else {
                                        if (pinprice > $.toFloat(sku.pinprice)) {
                                            pinsku = sku;
                                        }
                                    }
                                }

                                var strArr = [];
                                $.each(sku.choices, function (sc) {
                                    $.each(me.data.skuprops, function (p) {
                                        $.each(p.choices, function (c) {
                                            if ($.toInt(c.id) === $.toInt(sc.choiceid)) {
                                                strArr.push(c.name);
                                            }
                                        })
                                    });
                                });
                                sku.propnames = strArr.join(" | ");
                            });

                            //$.log("pins:"+$.toJson(oPins));
                            var first = true;
                            $.each(oPins, function (v, k) {
                                pins.push(v);

                                if (first) {
                                    pinsku = v;
                                    first = false;
                                }

                            });

                            me.setData({
                                "skus": skus,
                                pins: pins,
                                pinsku: pinsku
                            });
                            if (skus.length > 0) {
                                var oSku = skus[0];
                                //兼容旧数据的处理
                                oProduct.saleprice = oSku["saleprice"];
                                oProduct.marketprice = oSku["marketprice"];
                                me.setData({
                                    "product": oProduct
                                });
                            }
                            me.data.skutool.Skus = skus;
                            me.data.skutool.Props = me.data.skuprops;
                            var curSku = me.data.skutool.findLowest();
                            if (curSku) {
                                me.setData({
                                    "cursku.id": curSku.id,
                                    "cursku.icon": curSku.icon,
                                    "cursku.sn": curSku.sn,
                                    "cursku.price": new Decimal($.toFloat(curSku.saleprice)).toNumber(),
                                    "cursku.marketprice": new Decimal($.toFloat(curSku.marketprice)).toNumber(),
                                    "productDisplay.icon": curSku.icon,
                                    "productDisplay.price": new Decimal($.toFloat(curSku.saleprice)).toNumber(),
                                    "productDisplay.marketprice": new Decimal($.toFloat(curSku.marketprice)).toNumber(),
                                });
                            }

                        });
                });
        })

    },
    onUnload: function () {
        var me = this;
        if (me.data.timerPin) {
            clearInterval(me.data.timerPin)
        }
    },

    onShareAppMessage: function (e) {
        var me = this;

        var path = "/pages/product/detail?";

        var share={
            id:me.data.product.id
        };



        if( me.data.product.usedist ){
            share.isvip=1;

            var oUser = me.data.curUser;
            if( oUser && oUser.id ){
                share.fromUser = oUser.id;
            }
        }

        path += "share="+encodeURIComponent($.toJson(share));

        return {
            title: '商品分享',
            path: path,
            imageUrl: me.data.productDisplay.icon
        }

    },

    onViewPins: function (e) {
        var me = this;
        $.go("/pages/product/pin/more?productid=" + me.data.product.id)
    },
    onHome: function (e) {

        var me = this;

        wx.reLaunch({
            url: '/pages/index',
        })

    },
    onHaibao: function (e) {

        var me = this;

        if (!(me.data.curUser && me.data.curUser.id)) {
            $.errorBox("错误", "请先登录", function () {
                $.go("/pages/person/login");
            });
        } else {
            $.go("/pages/person/haibao/seltempl?productid=" + this.data.product.id)
            //$.go("/pages/product/haibaomake?id=" + this.data.product.id);
        }


    },
    onViewCart: function (e) {

        var me = this;

        $.go("/pages/index?tabindex=2");

    },
    onAddCart: function (e) {

        var me = this;

        me.setData({
            buynow: false,
            kaituan: false
        });
        me.showModal();

    },
    onClickBuyNow: function (e) {

        var me = this;

        me.setData({
            buynow: true,
            kaituan: false
        });
        me.showModal();

    },
    onClickPin: function (e) {
        var me = this;
        me.setData({
            buynow: false,
            kaituan: true
        });
        me.showModal();
    },
    onKaiTuan: function (e) {
        var me = this;
        /*me.setData({
            kaituan : true,
            buynow : true
        });
        me.showModal();*/
        if (!(me.data.curUser && me.data.curUser.id)) {
            $.errorBox("错误", "请先登录", function () {
                $.go("/pages/person/login");
            });
        } else {
            $.go("/pages/product/pin/kaituan?id=" + e.currentTarget.dataset.id);
        }

    },

    onClickHideModal: function (e) {
        var me = this;
        me.hideModal();
    },

    onNumChange: function (e) {
        var me = this;
        me.setData({
            num: e.detail.value
        })
    },
    onSkuChange: function (e) {
        var me = this;
        var sku = e.detail.sku;
        me.setData({
            "cursku.id": sku.id,
            "cursku.icon": sku.icon,
            "cursku.price": $.toFloat(sku.saleprice),
            "cursku.marketprice": $.toFloat(sku.marketprice),
            "cursku.sn": sku.sn
        });
    },
    onJoinPin: function (e) {
        var me = this;
        var id = $.toInt(e.currentTarget.dataset.id);
        var skuid = $.toInt(e.currentTarget.dataset.skuid);
        if (!(me.data.curUser && me.data.curUser.id)) {
            $.errorBox("错误", "请先登录", function () {
                $.go("/pages/person/login");
            });
        } else
            $.go("/pages/product/pin/joinpin?pinid=" + id + "&skuid=" + skuid);
    },
    onStartBuy: function (e) {

        var me = this;

        if (!(me.data.curUser && me.data.curUser.id)) {
            $.errorBox("错误", "请先登录", function () {
                $.go("/pages/person/login");
            });
        } else {
            var fnAfterSelSku = function (skuid) {
                if (!me.data.buynow && !me.data.kaituan) {

                    $.log("加入到购物车，skuid=" + skuid);
                    //加入购物车
                    $.api("mall.Cart.Add", {
                            "productid": me.data.product.id,
                            "name": me.data.product.name,
                            "skuid": skuid,
                            "num": me.data.num,
                            "fromuser":me.data.fromuser,
                            "propname": ($.toInt(skuid) ? me.data.skutool.getSkuNames(skuid, " | ") : "")
                        })
                        .then(function (value) {
                            wx.showToast({
                                title: '添加购物车成功',
                                icon: 'success',
                                duration: 2000,
                                success: function () {
                                    me.updateCartCount();
                                    me.hideModal();
                                }
                            })
                        })
                } else {
                    if (me.data.kaituan) {
                        //开团支付
                        $.go("/pages/product/kaituan?id=" + me.data.product.id + "&skuid=" + skuid + "&num=" + me.data.num);
                    } else {
                        //立即购买支付
                        $.go("/pages/product/buynow?id=" + me.data.product.id + "&skuid=" + skuid + "&num=" + me.data.num+"&fromuser="+me.data.fromuser);
                    }
                }
            };
            if (true) { //$.toInt(me.data.product.usesku)) {
                if ($.toInt(me.data.cursku.id)) {
                    fnAfterSelSku(me.data.cursku.id)
                } else {
                    wx.showToast({
                        title: '请选择规格',
                        icon: 'error',
                        duration: 2000
                    })
                }
            } else {
                $.log("not usesku!===");
                fnAfterSelSku(0)
            }
        }

    },

    showModal: function () {
        this.setData({
            isShow: true
        });
    },

    hideModal: function () {
        this.setData({
            isShow: false
        });
    },

    updateCartCount: function () {

        var me = this;
        if( $.toInt(me.data.curUser.id)){
            $.api("mall.Cart.LoadCount", {})
                .then(function (value) {
                    me.setData({
                        cartCount: $.toInt(value)
                    });
                })
        }

    },
    notifyLogin:function (oUser) {
        var me = this;
        if( oUser ){
            me.setData({"curUser":oUser});
        }
    }

});